﻿#include "stdafx.h"
#include "AstDef.h"
#include "AstType.h"
#include "SiContext.h"
#include "utility.h"
#include "ClassInstanceType.h"
#include "CodeGenerate/DefGen.h"
#include "CodeGenerate/GenList.h"
#include "AutoType.h"
#include "AstGetClass.h"

void AstDef::draw(std::ostream & os)
{
	std::string n = "def ";
	for (auto &i : vars) {
		n += i.name + ",";
	}
	n.pop_back();
	dotLable(os, n);
}

CodeGen * AstDef::makeGen(SiContext * parent)
{
	AstType* p = AutoType::isAuto(type) ? nullptr : type;

	if (vars.size() == 1) {
		auto gen= makeDefGen(parent, p, vars.at(0));
		parent->setSymbolValue(gen->name, gen );
		return gen;
	}
	
	auto list = new GenList();
	for (auto &i : vars) {
		auto gen = makeDefGen(parent, p, i);
		list->generates.push_back(gen);
		parent->setSymbolValue(i.name, gen);
	}

	return list;
}

DefGen * AstDef::makeDefGen(SiContext * parent, AstType * type, const Parameter & i)
{
	DefGen* x = new DefGen();
	x->name = i.name;
	x->type = type ? i.type : type;

	// 如果有值
	if (i.value) {
		CodeGen* p = i.value->makeGen(parent);
		x->value = p;	// p==null 说明是 = null 禁止创建

		if (AutoType::isAuto(type))
			x->type = p->type;
		else if(p && x->type->instanceOf(p->type) )	
			p->setHopeType(x->type); // def 确定了类型的情况，并且右值兼容，转为本类型
		return x;
	}
	else {
		// 如果是类定义
		auto * p = dynamic_cast<AstGetClass*>(x->type);
		if (p) {
			auto* cls = parent->findClass(x->type->name);
			static std::vector<std::pair<std::string, CodeGen*>> emptyArgs;
			ClassInstanceType* a = cls->getInstance(emptyArgs);
			x->type = a;
		}
	}
	
	// 如果没值，并且是自动类型，那么是一个占位符
	if (x->type->isAuto())
		return x;

	return x;
}
